package com.mediastory.spsserver.users.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mediastory.spsserver.users.dao.UsersDao;
import com.mediastory.spsserver.users.domain.Users;
import com.mediastory.spsserver.users.service.UsersSvc;

/**
 * @author Jaewon Choi
 *
 */

@Service
@Transactional
public class UsersSvcImpl implements UsersSvc {

	@Autowired
	UsersDao usersDao;
	
	public UsersSvcImpl() {
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public Users findbyAuth(String userId) throws Exception {
		// TODO Auto-generated method stub
		return usersDao.selectAuth(userId);
	}

	@Override
	public List<Users> findbyList(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		return (List<Users>) (usersDao.SelectList(condition));
	}

	public Map<String, Object> findbyListPaging(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("usersList", (List<Users>) (usersDao.SelectList(condition)));
		resultMap.put("usersListTotalCnt", (Integer) (usersDao.SelectListTotalCnt(condition)));
		
		return resultMap;
	}

	@Override
	public Users findby(Integer idx) throws Exception {
		// TODO Auto-generated method stub
		return usersDao.select(idx);
	}

	@Override
	public Users add(Users users) throws Exception {
		// TODO Auto-generated method stub
		
		//이용자 명수 확인
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("cIdx", users.getcIdx());
		int usersCnt = usersDao.SelectListTotalCnt(condition);
		
		//최대 5명 제한
		if(usersCnt>5){
			throw new Exception("[ERROR] 등록할 수 있는 이용자의 최대 개수를 초과하였습니다.");
		}
		
		//아이디 중복 체크
		condition.put("chkDupl", true);
		condition.put("idx", "0");
		condition.put("id", users.getId());
		if(findbyChkDupl(condition).equals("true")){
			throw new Exception("[ERROR] 이미 등록된 아이디 입니다.");
		}
		
		//등록
		Users result = usersDao.insert(users);
		
		return result;
	}

	@Override
	public Users modify(Users users) throws Exception {
		// TODO Auto-generated method stub
		return usersDao.update(users);
	}

	@Override
	public int remove(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return usersDao.delete(condition);
	}

	@Override
	public String findbyChkDupl(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		
		String result = "true";
		Integer cnt = (Integer) (usersDao.SelectListTotalCnt(condition));
		if(cnt != null && cnt == 0){
			result = "false";
		}
		
		return result;
	}

}